/**
 * 基础通用帮助工具类
 */
import config from '@/config/index.js';

/**
 * 验证手机号码
 */
const validPhone = function(phone) {
	if (!phone || !/^[1][3,4,5,7,8,9][0-9]{9}$/.test(phone)) {
		return false;
	}
	return true;
}

/**
 * 小程序Token失效，发事件给宿主APP
 */
const logoutMPToken = function() {
	uni.sendNativeEvent('invalid_token', {
		msg: 'Invalid Token!!!'
	}, ret => {
		uni.showModal({
			title: '提示',
			content: '用户登录状态失效，请重新登录！',
			showCancel: false
		}).finally(() => {
			uni.removeStorageSync("token")
			plus.runtime.quit()
		})
	})
}

/**
 * 关闭所有页面返回主页
 */
const goHome = function() {
	if (uni.getStorageSync('token')) {
		uni.reLaunch({
			url: config.homePage
		})
	} else {
		//登录页面，关闭后台运行小程序任务窗口
		rmoveAllMPWorkingLog()
		uni.reLaunch({
			url: config.loginPage
		}).finally(() => {})
	}
}
/**
 * 跳转页面
 * @param {Object} params
 * @param {type} 1: navigateTo  2:redirectTo
 */
const jumpPage = function(params, type = 1) {
	let _url = params.url;
	delete params.url;

	let _options = '';
	for (let key in params) {
		let _value = params[key] ? (typeof params[key] == 'object' ? encodeURIComponent(JSON.stringify(params[
			key])) : encodeURIComponent(params[key])) : '';
		_options += (_options ? `&${key}=${_value}` : `?${key}=${_value}`);
	}
	_url += _options;

	if (type == 1) {
		uni.navigateTo({
			url: _url
		})
	} else if (type == 2) {
		uni.redirectTo({
			url: _url
		})
	}
}

/**
 * 返回通用的文件存储路径
 * @param {String} url
 */
const getBucketUrl = function(url) {
	return url.indexOf('http') == 0 ? url : config.bucketUrl + url
}
/**
 * 返回通用的App或小程序应用路径
 * @param {String} url
 */
const getAppletUrl = function(url) {
	return url.indexOf('http') == 0 ? url : config.appletUrl + url
}

/**
 * 打开第三方应用
 * @param {Object} mp
 * @param {Object} item
 */
const openThirdApp = function(mp, item) {
	const appVersObj = item
	if (appVersObj.app_type === 3) { //网页
		jumpPage({
			url: '/pages/iframe/index',
			link: appVersObj.applet_link,
		})
		return;
	}
	if (appVersObj.app_type === 2) { //app	
		plus.runtime.openURL(appVersObj.applet_link, function(res) {
			plus.nativeUI.alert("本机未检测到该应用客户端");
		});
		return;
	}
	if (appVersObj.app_type === 1) { //小程序
		if (!mp) {
			uni.showToast({
				title: '不是uniapp支持的环境',
				icon: 'error'
			})
			return;
		}
		mp.getUniMPVersion(item.applet_id, (ret) => { //确认小程序是否已经下载安装
			// console.log(ret, item, compareVersion(appVersObj.applet_version, ret.versionInfo.name))
			if (0 == ret.code && compareVersion(appVersObj.applet_version, ret.versionInfo.name) != 1) {
				openUniApp(mp, item.applet_id)
				return;
			}
			//下载wgt，只有高版本才进行下载
			uni.showLoading({
				title: "小程序加载中..."
			});
			const downloadTask = uni.downloadFile({
				url: getAppletUrl(appVersObj.applet_url[0].path),
				success: (downloadRes) => {
					if (downloadRes.statusCode === 200) {
						uni.saveFile({
							tempFilePath: downloadRes.tempFilePath,
							success: (saveRes) => {
								const wgtFile = saveRes.savedFilePath;
								mp.installUniMP({ //安装
									appid: item.applet_id,
									wgtFile: wgtFile
								}, (r) => {
									if (0 != r.code) {
										uni.showModal({
											title: '加装小程序失败',
											content: JSON.stringify(
												r),
											showCancel: false
										})
										return;
									}
									openUniApp(mp, item.applet_id)
								});
							}
						})
					}
				},
				complete: () => {
					uni.hideLoading();
				}
			})
		});
	}
}

/**
 * 启动小程序
 * @param {Object} mp
 * @param {String} appid
 */
const openUniApp = function(mp, appid) {
	mp.openUniMP({ //获取成功 启动
		appid: appid
	}, (ret) => {
		if (ret.code == 0) {
			setMPWorkingLog(appid)
		} else {
			uni.showModal({
				title: '启动失败',
				content: JSON.stringify(ret),
				showCancel: false
			})
		}
	});
}

/**
 * 比较版本号，如果 version1 > version2 返回 1，如果 version1 < version2 返回 -1， 除此之外返回 0
 * @param {String} version1
 * @param {String} version2
 */
const compareVersion = function(version1, version2) {
	const arr1 = version1.split('.')
	const arr2 = version2.split('.')
	const length1 = arr1.length
	const length2 = arr2.length
	const minlength = Math.min(length1, length2)
	let i = 0
	for (i; i < minlength; i++) {
		let a = parseInt(arr1[i])
		let b = parseInt(arr2[i])
		if (a > b) {
			return 1
		} else if (a < b) {
			return -1
		}
	}
	if (length1 > length2) {
		for (let j = i; j < length1; j++) {
			if (parseInt(arr1[j]) != 0) {
				return 1
			}
		}
		return 0
	} else if (length1 < length2) {
		for (let j = i; j < length2; j++) {
			if (parseInt(arr2[j]) != 0) {
				return -1
			}
		}
		return 0
	}
	return 0
}

/**
 * 记录运行小程序
 * @param {String} appid
 */
const setMPWorkingLog = function(appid) {
	let listMP = []
	if (uni.getStorageSync('appMPWorkingInfo')) {
		listMP = JSON.parse(uni.getStorageSync('appMPWorkingInfo'))
	}
	listMP.push(appid)
	listMP = Array.from(new Set(listMP))
	uni.setStorageSync("appMPWorkingInfo", JSON.stringify(listMP))
}


/**
 * 获取运行小程序
 * @param {String} appid
 */
const getMPWorkingLog = function() {
	let listMP = []
	if (uni.getStorageSync('appMPWorkingInfo')) {
		listMP = JSON.parse(uni.getStorageSync('appMPWorkingInfo'))
	}
	return listMP
}

/**
 * 关闭后台运行小程序任务窗口
 * @param {String} appid
 */
const rmoveAllMPWorkingLog = function() {
	const mp = uni.requireNativePlugin('uniMP')
	let listMP = getMPWorkingLog()
	listMP.forEach(function(item) {
		mp.closeUniMP(item)
	})
	uni.removeStorageSync("appMPWorkingInfo")
}

export default {
	logoutMPToken,
	validPhone,
	goHome,
	jumpPage,
	getAppletUrl,
	openThirdApp,
	openUniApp,
	compareVersion,
	getMPWorkingLog,
	rmoveAllMPWorkingLog
}